package com.ibeeking.found.uaa.cs.config.auth.adapter;

import com.ibeeking.found.common.config.secret.RsaConfig;
import com.ibeeking.found.uaa.cs.config.auth.pwdencoder.CsPasswordEncoder;
import com.ibeeking.found.uaa.cs.service.ICsUserDetailsService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.PasswordEncoder;

import javax.annotation.Resource;


/**
 * @Author ibeeking
 */
@Order(2)
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    private ICsUserDetailsService userDetailsServiceImpl;
    @Resource
    private RsaConfig rsaConfig;

    //http://localhost:17010/oauth/authorize?client_id=found-b&response_type=code&scope=all&redirect_uri=http://localhost:17010/callback&state=121212
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 由于使用的是JWT，我们这里不需要csrf
        http.csrf().disable();

        http
                /**
                 * 定义哪些url需要被保护  哪些不需要保护
                 */
                .authorizeRequests()
                /**
                 * 定义这两个链接不需要登录可访问
                 */
                .antMatchers("/oauth/token", "oauth/check_token").permitAll()
                /**
                 * 其他的都需要登录
                 */
                .anyRequest().authenticated()
        ;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        /**
         * 使用自定义方式加载用户信息
         */
        auth.userDetailsService(userDetailsServiceImpl)
                .passwordEncoder(passwordEncoder());
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new CsPasswordEncoder(rsaConfig.getKeyPair());
    }

    /**
     * 让Security 忽略这些url，不做拦截处理
     *
     * @param web
     * @throws Exception
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/oauth/public_key", "/uaa/v1/oauth/publicKey", "/uaa/v1/oauth/refreshToken");
    }
}
